package org.isouland.cpwx.api.user;

import org.isouland.cpwx.api.core.util.HttpUtil;
import org.isouland.cpwx.api.user.req.WxUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

public class WxUserAPI {
	private static Logger logger = LoggerFactory.getLogger(WxUserAPI.class);
	
	public static final String userinfo_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
	
	public static WxUserInfo getUserInfo(String accessToken, String openId) {
	    WxUserInfo wxUserInfo = null;
	    String requestUrl = userinfo_url.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
	    // 获取用户信息
	    JSONObject jsonObject = HttpUtil.sendGet(requestUrl);
	    if (null != jsonObject) {
	      try {
	    	  wxUserInfo = new WxUserInfo();
	          // 用户的标识
	    	  wxUserInfo.setOpenId(jsonObject.getString("openid"));
	          // 关注状态（1是关注，0是未关注），未关注时获取不到其余信息
	    	  wxUserInfo.setSubscribe(jsonObject.getInteger("subscribe"));
	          // 用户关注时间
	    	  wxUserInfo.setSubscribeTime(jsonObject.getString("subscribe_time"));
	          // 昵称
	    	  wxUserInfo.setNickname(jsonObject.getString("nickname"));
	          // 用户的性别（1是男性，2是女性，0是未知）
	    	  wxUserInfo.setSex(jsonObject.getInteger("sex"));
	          // 用户所在国家
	    	  wxUserInfo.setCountry(jsonObject.getString("country"));
	          // 用户所在省份
	    	  wxUserInfo.setProvince(jsonObject.getString("province"));
	          // 用户所在城市
	    	  wxUserInfo.setCity(jsonObject.getString("city"));
	          // 用户的语言，简体中文为zh_CN
	    	  wxUserInfo.setLanguage(jsonObject.getString("language"));
	          // 用户头像
	    	  wxUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
	        } catch (Exception e) {
	       /* if (0 == wxUserInfo.getSubscribe()) {
	        	logger.info("用户{}已取消关注", wxUserInfo.getOpenId());
	        } else {*/
	            int errorCode = jsonObject.getInteger("errcode");
	            String errorMsg = jsonObject.getString("errmsg");
	            logger.info("获取用户信息失败 errcode:{} errmsg:{}", errorCode, errorMsg);
	            wxUserInfo = null;
	        //}
	      }
	    }
	    return wxUserInfo;
	  }
	
}
